/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Database;

import Entity.Comment;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Sony
 */
public class CommentData {
    public static ArrayList<Comment> getCommentById(int id) throws ClassNotFoundException, SQLException{
        ArrayList<Comment> listcomment = new ArrayList<Comment>();
        Connection cn = DataAcess.ConnectionDatabase();      
        try {
            String sql = "select * from Comment where post_id = ? Order By id DESC";
            PreparedStatement ps = cn.prepareStatement(sql);
            ps.setInt(1,id);
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                Comment cm = new Comment();
                cm.setId(rs.getInt("id"));
                cm.setPost_id(rs.getInt("post_id"));
                cm.setUsers_id(rs.getInt("users_id"));
                cm.setContent(rs.getString("content"));
                listcomment.add(cm);
            }
            return listcomment;
        } catch (SQLException ex) {
            Logger.getLogger(CommentData.class.getName()).log(Level.SEVERE, null, ex);
            return null;          
        }finally{
            cn.close();
        }
    }
    
    public static boolean insertComment(Comment cm) throws ClassNotFoundException, SQLException{
        Connection cn = DataAcess.ConnectionDatabase();
        try {           
            String sql = "insert into Comment(post_id, users_id, content) values(?,?,?)";
            PreparedStatement ps = cn.prepareStatement(sql);
            ps.setInt(1, cm.getPost_id());
            ps.setInt(2, cm.getUsers_id());
            ps.setString(3, cm.getContent());
            int rs = ps.executeUpdate();
            return rs > 0;
        } catch (SQLException ex) {
            Logger.getLogger(CommentData.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }finally{
            cn.close();
        }
    }
}
